const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const common = require('../../core/common');
const stringUtils = require('../../core/util/StringUtils');
const _ = require('lodash');

exports.add = async(ctx) => {
    let house_type_name = ctx.request.body.house_type_name || '';
    let project_id = ctx.request.body.project_id || 0;
    let area = ctx.request.body.area || '';
    let pic = ctx.request.body.pic || '';
    if (house_type_name === '' || project_id <= 0 || area === '') {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        let existproject = await mysql.query(`SELECT * FROM project WHERE project_id = ?`, project_id);
        if (existproject.length <= 0){
            ctx.body = {
                result: 204,
                message: "找不到对应项目"
            };
            return
        }
        let newHouseType = {
            house_type_name,
            project_id,
            area,
            pic
        };
        ret = await mysql.query(`INSERT INTO house_type SET ?`, newHouseType);
        if (!ret || ret.insertId === -1){
            ctx.body = {
                result: 202,
                message: "新增户型失败"
            };
        } else {
            ctx.body = {
                result: 200,
                id: ret.insertId,
                message: "新增户型成功"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.copy = async(ctx) => {
    let house_type_id = ctx.request.body.house_type_id || '';
    if (house_type_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        let existRows = await mysql.query(`SELECT * FROM house_type WHERE house_type_id = ?`, house_type_id);
        let existRooms = await mysql.query(`SELECT * FROM room WHERE house_type_id = ? `, house_type_id);
        let sqlRoomIDs = '(';
        for (i = 0; i < existRooms.length; i++){
            sqlRoomIDs += (i !== existRooms.length -1) ? (existRooms[i].room_id + ',') : (existRooms[i].room_id + ')');
        }
        let existRoomDevices = (existRooms.length > 0) ? await mysql.query(`SELECT * FROM t_room_v_device WHERE room_id IN ${sqlRoomIDs} `) : "";
        let existScenario = await mysql.query(`SELECT * FROM scenario WHERE house_type_id = ? `, house_type_id);
        let sqlScenarioIDs = '(';
        for (i = 0; i < existScenario.length; i++){
            sqlScenarioIDs += (i !== existScenario.length -1) ? (existScenario[i].scenario_id + ',') : (existScenario[i].scenario_id + ')');
        }
        let existScenarioDevices = (existScenario.length > 0) ? await mysql.query(`SELECT * FROM t_scenario_v_device WHERE scenario_id IN ${sqlScenarioIDs} `) : "";
        if (existRows.length <= 0){
            ctx.body = {
                result: 204,
                message: "找不到对应户型"
            };
            return
        }
        newHouseType = {
            house_type_name:existRows[0].house_type_name,
            project_id:existRows[0].project_id,
            area:existRows[0].area,
            pic:existRows[0].pic
        }
        newHouseType.house_type_name += 'copy';
        await new Promise((resolve, reject) => {
            var trans = mysql.Client.startTransaction();

            trans.query(`INSERT INTO house_type SET ?`,newHouseType, function(err, info) {
                if(err){
                    trans.rollback();
                    ctx.body = {
                        result: 202,
                        message: "copy户型失败"
                    };
                    resolve(ctx);
                } else{
                    if (existRooms.length > 0){
                        let create_time = moment().format('YYYY-MM-DD HH:mm:ss');
                        let update_time = moment().format('YYYY-MM-DD HH:mm:ss');
                        let sqlInsertRooms = `INSERT INTO room (room_name,house_type_id,area,create_time,update_time) VALUES  `;
                        for (let room of Object.values(existRooms)) {
                            sqlInsertRooms += `('${room.room_name}', ${info.insertId}, ${room.area}, '${create_time}', '${update_time}'),`;
                        }
                        sqlInsertRooms = sqlInsertRooms.substr(0,sqlInsertRooms.length-1);
                        trans.query(sqlInsertRooms, function(err,insertRoomsResult) {
                            if(err){
                                trans.rollback();
                                ctx.body = {
                                    result: 202,
                                    message: "copy户型失败" + err.toString()
                                };
                                resolve(ctx);
                            } else{
                                let dicRooms = {};
                                let dicRoomDevices = {};
                                let sqlInsertRoomDevices = `INSERT INTO t_room_v_device (product_id,room_id,name,tag) VALUES  `;
                                let roomDevicesCount = 0;
                                for (i = 0; i < existRooms.length; i++) {
                                    dicRooms[existRooms[i].room_id] = insertRoomsResult.insertId + i;
                                }
                                if (existRoomDevices.length > 0){
                                    for (let roomDevice of Object.values(existRoomDevices)) {
                                        sqlInsertRoomDevices += `(${roomDevice.product_id }, ${dicRooms[roomDevice.room_id]}, '${roomDevice.name}', "${roomDevice.tag}" ),`;
                                        roomDevicesCount++;
                                        dicRoomDevices[roomDevice.v_device_id] = 0;
                                    }
                                }
                                if (roomDevicesCount > 0) {
                                    sqlInsertRoomDevices = sqlInsertRoomDevices.substr(0,sqlInsertRoomDevices.length-1);
                                    trans.query(sqlInsertRoomDevices, function(err,insertRoomDevicesResult) {
                                        if(err){
                                            trans.rollback();
                                            ctx.body = {
                                                result: 202,
                                                message: "copy户型失败" + err.toString()
                                            };
                                            resolve(ctx);
                                        }else{
                                            let index = 0;
                                            for (let key in dicRoomDevices) {
                                                dicRoomDevices[key] = insertRoomDevicesResult.insertId + index++;
                                            }
                                            if (existScenario.length > 0){
                                                let sqlInsertScenarios = `INSERT INTO scenario (scenario_name,icon_id,room_id,house_type_id,is_deleted,create_time,update_time) VALUES  `;
                                                for (let scenario of Object.values(existScenario)) {
                                                    if (scenario.room_id){
                                                        sqlInsertScenarios += `('${scenario.scenario_name }', ${scenario.icon_id}, ${dicRooms[scenario.room_id]}, ${info.insertId}, ${scenario.is_deleted}, '${create_time}', '${update_time}'),`;
                                                    } else{
                                                        sqlInsertScenarios += `('${scenario.scenario_name }', ${scenario.icon_id}, null, ${info.insertId}, ${scenario.is_deleted}, '${create_time}', '${update_time}'),`;
                                                    }
                                                }
                                                sqlInsertScenarios = sqlInsertScenarios.substr(0,sqlInsertScenarios.length-1);
                                                trans.query(sqlInsertScenarios, function(err,insertScenarioResult) {
                                                    if(err){
                                                        trans.rollback();
                                                        ctx.body = {
                                                            result: 202,
                                                            message: "copy户型失败" + err.toString()
                                                        };
                                                        resolve(ctx);
                                                    }else{
                                                        let scenarioDevicesCount = 0;
                                                        let dicScenario = {};
                                                        let sqlInsertScenarioDevices = `INSERT INTO t_scenario_v_device (v_device_id,scenario_id,property_values,type) VALUES  `;
                                                        for (i = 0; i < existScenario.length; i++) {
                                                            dicScenario[existScenario[i].scenario_id] = insertScenarioResult.insertId + i;
                                                        }
                                                        if (existScenarioDevices.length > 0){
                                                            for (let scenarioDevice of Object.values(existScenarioDevices)) {
                                                                sqlInsertScenarioDevices += `(${dicRoomDevices[scenarioDevice.v_device_id]}, ${dicScenario[scenarioDevice.scenario_id]}, '${scenarioDevice.property_values}', ${scenarioDevice.type} ),`;
                                                                scenarioDevicesCount++;
                                                            }
                                                        }
                                                        if (scenarioDevicesCount > 0){
                                                            sqlInsertScenarioDevices = sqlInsertScenarioDevices.substr(0,sqlInsertScenarioDevices.length-1)
                                                            trans.query(sqlInsertScenarioDevices, function(err,insertScenarioDevicesResult) {
                                                                if(err){
                                                                    trans.rollback();
                                                                    ctx.body = {
                                                                        result: 202,
                                                                        message: "copy户型失败" + err.toString()
                                                                    };
                                                                    resolve(ctx);
                                                                }else{
                                                                    trans.commit();
                                                                    ctx.body = {
                                                                        result: 200,
                                                                        id: info.insertId,
                                                                        message: "copy户型成功"
                                                                    };
                                                                    resolve(ctx);
                                                                }
                                                            });
                                                        } else{
                                                            trans.commit();
                                                            ctx.body = {
                                                                result: 200,
                                                                id: info.insertId,
                                                                message: "copy户型成功"
                                                            };
                                                            resolve(ctx);
                                                        }
                                                    }
                                                });
                                            } else {
                                                trans.commit();
                                                ctx.body = {
                                                    result: 200,
                                                    id: info.insertId,
                                                    message: "copy户型成功"
                                                };
                                                resolve(ctx);
                                            }
                                        }
                                    });
                                }else{
                                    trans.commit();
                                    ctx.body = {
                                        result: 200,
                                        id: info.insertId,
                                        message: "copy户型成功"
                                    }
                                    resolve(ctx);
                                }
                            }
                        });
                    } else{
                        trans.commit();
                        ctx.body = {
                            result: 200,
                            id: info.insertId,
                            message: "copy户型成功"
                        }
                        resolve(ctx);
                    }
                }
            });
            trans.execute();
        });
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}


exports.delete = async(ctx) => {
    let house_type_id = ctx.params.house_type_id || 0;
    if (house_type_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        ret = await mysql.query(`delete from house_type WHERE house_type_id = ?`, house_type_id);
        if (!ret || ret.affectedRows === 0){
            ctx.body = {
                result: 202,
                message: "对象不存在或已删除"
            };
        } else {
            ctx.body = {
                result: 200,
                message: "删除成功"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.update = async(ctx) => {
    let house_type_id = ctx.request.body.house_type_id || 0;
    let house_type_name = ctx.request.body.house_type_name || '';
    // let project_id = ctx.request.body.project_id || 0;
    let area = ctx.request.body.area || '';
    if (house_type_id <= 0 || house_type_name === '' || area === '') {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        let selectRows = await mysql.query(`SELECT * FROM house_type WHERE house_type_id = ?`, house_type_id);
        if (selectRows.length > 0) {
            console.log('selectRows:', selectRows);
            selectRows[0].house_type_name = house_type_name;
            selectRows[0].area = area;
            ret = await mysql.query(`UPDATE house_type SET ? WHERE house_type_id = ?`, [selectRows[0],house_type_id]);
            if (!ret || ret.insertId === -1) {
                ctx.body = {
                    result: 202,
                    message: "更新失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    message: "更新成功"
                };
            }
        } else {
            ctx.body = {
                result: 203,
                message: "对象不存在或者已删除"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.getList = async(ctx) => {
    let create_user_id = ctx.user.id || '';
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;
    let project_id = ctx.query.project_id || 0;

    if (create_user_id === ''){
        ctx.body = {
            result: 201,
            message: "无效的user_id"
        };
        return;
    }
    if (project_id < 0){
        ctx.body = {
            result: 202,
            message: "无效的project_id"
        };
        return;
    }
    try {
        let results = (project_id === 0) ? await mysql.query(`SELECT * FROM house_type ORDER BY house_type_id LIMIT ${indexfrom}, ${counts} ` )
            : await mysql.query(`SELECT * FROM house_type WHERE project_id = ${project_id} ORDER BY house_type_id LIMIT ${indexfrom}, ${counts} ` );
        let totalResult = (project_id === 0) ? await mysql.query(`SELECT COUNT(house_type_id) AS total FROM house_type`)
            : await mysql.query(`SELECT COUNT(house_type_id) AS total FROM house_type WHERE project_id = ${project_id} `);
        ctx.body = {
            result: 200,
            list:results,
            totalpage:Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0)/counts),
            totalcounts:totalResult.length > 0 ? totalResult[0].total : 0,
            message: "查询成功"
        };
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}

exports.getDetail = async(ctx) => {
    let house_type_id = ctx.params.house_type_id || 0;

    if (house_type_id <= 0){
        ctx.body = {
            result: 201,
            message: "无效的house_type_id"
        };
        return;
    }
    try {
        let selectHouseType = await mysql.query(`SELECT * FROM house_type where house_type_id = ${house_type_id}`);
        if (selectHouseType.length > 0){
            roomResult = selectHouseType[0];
            selectScenarios = await mysql.query(`SELECT * FROM scenario where house_type_id = ${house_type_id}`);
            selectRooms = await mysql.query(`SELECT room_id,room_name,area FROM room where house_type_id = ${house_type_id}`);
            if (selectRooms.length > 0){
                for (let room of Object.values(selectRooms)){
                    let totalResult = await mysql.query(`SELECT count(v_device_id) AS total FROM t_room_v_device where room_id = ${room.room_id}`);
                    room.prodcut_counts = (totalResult.length > 0 ? totalResult[0].total : 0);
                }
            }
            roomResult.room_count = selectRooms.length;
            roomResult.scenario_list = selectScenarios;
            roomResult.room_list = selectRooms;
            ctx.body = {
                result: 200,
                resultInfo:roomResult,
                message: "查询成功"
            };
        }else{
            ctx.body = {
                result: 202,
                message: "查询失败"
            };
        }

    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}